import 'package:flutter/material.dart';
import 'package:rxdart/rxdart.dart';
import 'package:schoollifedemo/base/common_function.dart';
import 'package:schoollifedemo/base/url_contract.dart';
import 'package:schoollifedemo/commonwidget/common_base_viewmodel.dart';
import 'package:schoollifedemo/entity/Entity.dart';

class MemorandumEditPageViewModel extends BaseViewModel {
  SingleMemorandumResponse? _memorandumResponse;

  SingleMemorandumResponse? get memorandumResponse => _memorandumResponse;

  BehaviorSubject loadingState = BehaviorSubject<CommonLoadingState?>();

  String? currentNoteId;

  // 拉取当前的备忘录条目
  Future<void> pullCurrentNote({
    required String noteId,
    OnSuccess? onSuccess,
    OnFailure? onFailure,
  }) async {
    final params = <String, Object>{};
    params['account'] = getApplication().getLoginAccount() ?? '';
    params['note_id'] = noteId;
    final result = await getNetworkUtil().postHttp(
      UrlContract.pullUserMemorandum,
      params: params,
    );
    final resp = SingleMemorandumResponse.fromMap(result);
    if (resp.status == 0) {
      _memorandumResponse = resp;
      loadingState.add(CommonLoadingState.successTypeOne);
      if (onSuccess != null) {
        onSuccess();
      }
    } else {
      loadingState.add(CommonLoadingState.failure);
      if (onFailure != null) {
        onFailure(resp.msg);
      }
    }
  }

  // 返回上一页
  Future<void> backPage(BuildContext context) async {
    await getApplication().routerPop(context);
  }

  // 创建新的备忘录
  Future<void> saveNewMemorandum({
    String? title, // 标题
    required String msg, // 记录信息
    required DateTime createTime, // 创建时间
    OnSuccess? onSuccess, // 成功回调
    OnFailure? onFailure, // 失败回调
  }) async {
    final params = <String, Object?>{};
    params['account'] = getApplication().getLoginAccount() ?? '';
    params['note_id'] = await getChannelService()
        .getCommonChannelFunc()
        ?.convertMD5((getApplication().getLoginAccount() ?? '') +
            '${createTime.millisecondsSinceEpoch}');
    currentNoteId = params['note_id'].toString();
    if (title == null || title.isEmpty) {
      if (msg.length > 10) {
        params['title'] = msg.substring(0, 10);
      } else {
        params['title'] = msg;
      }
    } else {
      params['title'] = title;
    }
    params['msg'] = msg;
    params['record_start_time'] = createTime.millisecondsSinceEpoch;
    params['last_edit_time'] = createTime.millisecondsSinceEpoch;
    final result = await getNetworkUtil()
        .postHttp(UrlContract.addUserMemorandum, params: params);
    final resp = CommonResponse.fromMap(result);
    if (resp.status == 0) {
      if (onSuccess != null) {
        onSuccess();
      }
    } else {
      if (onFailure != null) {
        onFailure(resp.msg);
      }
    }
  }

  // 删除用户备忘录
  Future<void> deleteMemorandum({
    OnSuccess? onSuccess,
    OnFailure? onFailure,
  }) async {
    final params = <String, Object?>{};
    params['note_id'] = currentNoteId;
    params['account'] = getApplication().getLoginAccount() ?? '';
    final result = await getNetworkUtil()
        .postHttp(UrlContract.deleteUserMemorandum, params: params);
    final resp = CommonResponse.fromMap(result);
    if (resp.status == 0) {
      if (onSuccess != null) {
        onSuccess();
      }
    } else {
      if (onFailure != null) {
        onFailure(resp.msg);
      }
    }
  }

  // 更改用户备忘录
  Future<void> modifyMemorandum({
    String? title, // 标题
    required String msg, // 记录信息
    OnSuccess? onSuccess,
    OnFailure? onFailure,
  }) async {
    final params = <String, Object?>{};
    params['note_id'] = currentNoteId;
    params['account'] = getApplication().getLoginAccount() ?? '';
    if (title == null || title.isEmpty) {
      if (msg.length > 10) {
        params['title'] = msg.substring(0, 10);
      } else {
        params['title'] = msg;
      }
    } else {
      params['title'] = title;
    }
    params['msg'] = msg;
    params['last_edit_time'] = DateTime.now().millisecondsSinceEpoch;
    final result = await getNetworkUtil()
        .postHttp(UrlContract.modifyUserMemorandum, params: params);
    final resp = CommonResponse.fromMap(result);
    if (resp.status == 0) {
      if (onSuccess != null) {
        onSuccess();
      }
    } else {
      if (onFailure != null) {
        onFailure(resp.msg);
      }
    }
  }

  // 创建普通状态
  void commonState() {
    loadingState.add(CommonLoadingState.successTypeOne);
  }

  // 获取备忘录创建时间
  String getCreateTime({DateTime? time}) {
    final recordStartTimeStr =
        _memorandumResponse?.memorandumEntity?.recordStartTime;
    int? recordStartTime = int.tryParse(recordStartTimeStr ?? '');
    final dateTime = DateTime.fromMillisecondsSinceEpoch(
        (recordStartTime ?? time?.millisecondsSinceEpoch ?? 0));
    if (dateTime.minute < 10) {
      return '${dateTime.year}年${dateTime.month}月${dateTime.day}日 ${dateTime.hour}:0${dateTime.minute}';
    }

    return '${dateTime.year}年${dateTime.month}月${dateTime.day}日 ${dateTime.hour}:${dateTime.minute}';
  }

  // 获取备忘录上次修改时间
  String getLastEditTime({DateTime? time}) {
    final lastEditTimeStr = _memorandumResponse?.memorandumEntity?.lastEditTime;
    int? lastEditTime = int.tryParse(lastEditTimeStr ?? '');
    final dateTime = DateTime.fromMillisecondsSinceEpoch(
        (lastEditTime ?? time?.millisecondsSinceEpoch ?? 0));
    if (dateTime.minute < 10) {
      return '${dateTime.year}年${dateTime.month}月${dateTime.day}日 ${dateTime.hour}:0${dateTime.minute}';
    }
    return '${dateTime.year}年${dateTime.month}月${dateTime.day}日 ${dateTime.hour}:${dateTime.minute}';
  }
}
